<template>
  <div class="vocab-test-container">
    <!-- 背景装饰 -->
    <div class="background-decoration"/>

    <!-- 测试卡片 -->
    <div class="test-card">
      <!-- 顶部进度与返回 -->
      <div class="test-header">
        <button class="back-btn" :disabled="isProcessing" @click="goBack">
          <i class="fa-solid fa-circle-left"/>
        </button>
        <div class="progress-container">
          <!--          <div class="progress-text">当前水平：{{ currentQuestion.grade }}</div>-->
          <div class="progress-text">第 {{ currentQuestionIndex + 1 }} / {{ totalQuestions }} 题
            <!--            {{ currentQuestion.correctAnswer }}-->
          </div>
          <div class="progress-bar">
            <div class="progress-fill" :style="{ width: progressPercentage + '%' }"/>
          </div>
        </div>
      </div>

      <!-- 题目内容区域 -->
      <div class="question-container">
        <div class="question-word">{{ currentQuestion.word }}</div>
        <div class="question-prompt">请选择最符合的释义：</div>

        <!-- 选项列表（每个选项独占一行） -->
        <div class="options-list">
          <button
            v-for="(option, index) in currentQuestion.options"
            :key="index"
            class="option-btn"
            :class="{
              'option-selected': selectedOption === index,
              'option-correct': isProcessing && index === currentQuestion.correctAnswer,
              'option-incorrect': isProcessing && selectedOption === index && selectedOption !== currentQuestion.correctAnswer,
              'option-highlight': isProcessing
            }"
            :disabled="isProcessing || hasSelected || isShowingStrategyTip"
            @click="selectOption(index)"
          >
            {{ option }}
          </button>

          <!-- 不认识按钮 -->
          <button
            class="dont-know-btn"
            :class="{
              'btn-active': selectedAsUnknown,
              'option-incorrect': isProcessing && selectedAsUnknown,
              'option-highlight': isProcessing
            }"
            :disabled="isProcessing || hasSelected || isShowingStrategyTip"
            @click="markAsUnknown"
          >
            <i class="icon-unknown"/> 不认识
          </button>

          <!-- 测试数据状态栏 -->
          <div class="test-stats-bar">
            <div class="stat-item correct">
              <i class="fa-solid fa-check"></i>
              <span class="stat-label">正确</span>
              <span class="stat-value">{{ rightAnswerCount }}</span>
            </div>
            <div class="stat-item wrong">
              <i class="fa-solid fa-times"></i>
              <span class="stat-label">错误</span>
              <span class="stat-value">{{ wrongAnswerCount }}</span>
            </div>
            <div class="stat-item guess">
              <i class="fa-solid fa-question"></i>
              <span class="stat-label">猜测</span>
              <span class="stat-value">{{ guessWord }}</span>
            </div>
            <div class="stat-item error-streak">
              <i class="fa-solid fa-arrow-trend-down"></i>
              <span class="stat-label">连错</span>
              <span class="stat-value">{{ continuousErrorCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 策略调整提示弹窗（Totast 效果） -->
    <div
      class="strategy-tip"
      :class="{ 'tip-show': isShowingStrategyTip, 'tip-type-down': tipType === 'down', 'tip-type-up': tipType === 'up' }"
    >
      <div class="tip-icon">
        <i v-if="tipType === 'down'" class="fa-solid fa-rotate"></i>
        <i v-if="tipType === 'up'" class="fa-solid fa-arrow-up"></i>
      </div>
      <div class="tip-content">
        <div class="tip-title">{{ tipTitle }}</div>
        <div class="tip-desc">{{ tipDesc }}</div>
      </div>
    </div>
  </div>
</template>

<script>
import AudioCacheUtil from '@/utils/AudioCacheUtil'
import { endVocalTest, question } from '@/api/vocabTest'
import { int } from 'mockjs/src/mock/random/basic'

export default {
  name: 'VocabTestStart',
  data() {
    return {
      rightAnswerCount: 0, // 回答正确数
      wrongAnswerCount: 0, // 回答错误数
      continuousErrorCount: 0, // 连续错误数
      continuousRightCount: 0, // 连续错误数
      guessWord: 0, // 疑似被猜测的单词数（错误单词数）
      currentQuestionIndex: 0,
      totalQuestions: 0, // 与示例题库数量保持一致
      selectedOption: null,
      selectedAsUnknown: false,
      isProcessing: false, // 用于控制反馈动画期间的状态
      isShowingStrategyTip: false, // 是否显示策略调整提示
      tipType: 'down', // 提示类型：down（降级）、up（升级）
      tipTitle: '', // 提示标题
      tipDesc: '', // 提示描述
      questions: []
    }
  },
  computed: {
    currentQuestion() {
      // 优化：仅在题目切换时播放音频，避免重复触发
      const currentQ = this.questions[this.currentQuestionIndex]
      if (currentQ && !this.isProcessing && !this.isShowingStrategyTip) {
        // 可添加防抖逻辑，防止频繁切换时重复播放
        AudioCacheUtil.play(currentQ.word, 'en')
      }
      return currentQ || {}
    },
    progressPercentage() {
      return this.totalQuestions ? ((this.currentQuestionIndex + 1) / this.totalQuestions) * 100 : 0
    },
    hasSelected() {
      return this.selectedOption !== null || this.selectedAsUnknown
    }
  },
  mounted() {
    this.reqData()
  },
  methods: {
    async reqData() {
      const res = await question({
        rightNum: this.rightAnswerCount,
        wrongNum: this.wrongAnswerCount,
        guessNum: this.guessWord,
        continueWrongNum: this.continuousErrorCount
      })
      this.questions = res
      if (this.questions.length === 1 && this.questions[0].vocalTestLevel && this.questions[0].vocalTestWordNumber) {
        // 测试结束 跳转结果页面 跳转时携带参数（通过query传递）
        this.$router.push({
          name: 'VocabTestResult',
          query: {
            level: this.questions[0].vocalTestLevel, // 如 'B1'
            vocabCount: this.questions[0].vocalTestWordNumber // 如 4500
          }
        })
      }
      this.questions.forEach(question => {
        question.correctAnswer = Number(question.correctAnswer) // 确保是数字类型
      })
      this.totalQuestions = this.questions.length
    },
    async refresh() {
      this.currentQuestionIndex = 0
      this.questions = []
      await this.reqData() // 重新请求题目（触发降级/升级后的新题库）
      this.rightAnswerCount = 0
      this.wrongAnswerCount = 0
      this.continuousErrorCount = 0
      this.guessWord = 0
    },
    // 显示策略调整提示
    showStrategyTip(type, title, desc) {
      this.tipType = type
      this.tipTitle = title
      this.tipDesc = desc
      this.isShowingStrategyTip = true
      this.isProcessing = false // 关闭答案处理状态

      // 3秒后自动关闭提示
      setTimeout(() => {
        this.isShowingStrategyTip = false
      }, 3000)
    },
    goBack() {
      if (this.isProcessing || this.isShowingStrategyTip) return
      // 退出确认
      this.$confirm(
        '是否退出测试？',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        this.$router.push('/vocabularyTestHome')
        endVocalTest()
      })
    },
    selectOption(index) {
      if (this.isProcessing || this.isShowingStrategyTip) return

      const isCorrect = index === this.currentQuestion.correctAnswer
      if (isCorrect) {
        this.rightAnswerCount++
        this.continuousErrorCount = 0
        this.continuousRightCount++ // 连对题目数

        let rightRadio = this.rightAnswerCount / this.questions.length
        if (this.continuousRightCount >= 6) {
          rightRadio = this.rightAnswerCount / (this.rightAnswerCount + this.wrongAnswerCount)
          if (rightRadio >= 0.80) {
            rightRadio = 0.85
            this.continuousRightCount = 0
            this.rightAnswerCount = Math.floor(this.questions.length * 0.85)
          }
        }

        // 触发策略升级：正确率大于85%
        if (rightRadio >= 0.85) {
          this.showStrategyTip(
            'up',
            '测试难度升级',
            '恭喜！你已连续答对多题，即将为你提升题目难度'
          )
          // 延迟刷新题库（等待提示显示完毕）
          setTimeout(() => {
            this.refresh()
          }, 1000)
          return
        }
      } else {
        this.guessWord++
        this.wrongAnswerCount++
        this.continuousErrorCount++
        this.continuousRightCount = 0

        // 触发策略降级：连续错误3次 或 错误率大于15%
        if (this.continuousErrorCount >= 3 || this.wrongAnswerCount / this.questions.length >= 0.15) {
          this.showStrategyTip(
            'down',
            '策略更新',
            '更换匹配难度！'
          )
          // 延迟刷新题库
          setTimeout(() => {
            this.refresh()
          }, 1000)
          return
        }

        // 猜测提示（原逻辑保留）
        if (this.guessWord === 1) {
          const guessWordWaringSound = new Audio(require('@/assets/vocal-test-waring.mp3'))
          guessWordWaringSound.play()
          this.$msgbox.alert('为确保测试结果准确性，不认识的单词请直接选择不认识！', '提示', {
            confirmButtonText: '确定',
            showClose: false,
            closeOnClickModal: false,
            type: 'warning'
          })
        }
      }

      this.selectedOption = index
      this.selectedAsUnknown = false
      this.processAnswer()
    },
    markAsUnknown() {
      if (this.isProcessing || this.isShowingStrategyTip) return

      this.wrongAnswerCount++
      this.continuousErrorCount++

      // 不认识按钮触发降级（示例条件）
      if (this.continuousErrorCount > 2) {
        this.showStrategyTip(
          'down',
          '测试难度调整',
          '已连续多题选择“不认识”，即将为你降低题目难度'
        )
        setTimeout(() => {
          this.refresh()
        }, 1000)
        return
      }

      this.selectedAsUnknown = true
      this.selectedOption = null
      this.processAnswer()
    },
    processAnswer() {
      this.isProcessing = true

      // 停顿1秒展示反馈效果
      setTimeout(() => {
        if (this.currentQuestionIndex < this.questions.length - 1) {
          this.currentQuestionIndex++
          this.resetSelection()
        } else {
          // 最后一题提交结果
          this.$router.push('/vocab-test/result')
        }
      }, 1000)
    },
    resetSelection() {
      this.selectedOption = null
      this.selectedAsUnknown = false
      this.isProcessing = false
    }
  }
}
</script>

<style scoped>
* {
  user-select: none;
}

.vocab-test-container {
  min-height: 100vh;
  max-height: 100vh;
  display: flex;
  justify-content: center;
  padding: 20px;
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
}

.background-decoration {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, #E6F0FF 0%, #FFFFFF 100%);
  z-index: 1;
}

.test-card {
  width: 100%;
  max-width: 550px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 25px clamp(15px, 8vw, 30px);
  position: relative;
  z-index: 2;
  display: flex;
  flex-direction: column;
  height: 100%;
}

/* 头部进度区域 */
.test-header {
  display: flex;
  align-items: center;
  margin-bottom: 30px;
}

.back-btn {
  background: transparent;
  border: none;
  color: #6B7280;
  font-size: 20px;
  cursor: pointer;
  width: 36px;
  height: 36px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s;
  margin-right: 15px;
}

.back-btn:hover:not(:disabled) {
  background: #F3F4F6;
  color: #3B82F6;
}

.back-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.progress-container {
  flex: 1;
}

.progress-text {
  font-size: 14px;
  color: #6B7280;
  margin-bottom: 8px;
  text-align: right;
}

.progress-bar {
  height: 6px;
  background: #F3F4F6;
  border-radius: 3px;
  overflow: hidden;
}

.progress-fill {
  height: 100%;
  background: #3B82F6;
  border-radius: 3px;
  transition: width 0.3s ease;
}

/* 题目内容区域 */
.question-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.question-word {
  font-size: 28px;
  font-weight: 700;
  color: #1F2937;
  margin-bottom: 10px;
  font-family: 'Poppins', 'Inter', sans-serif;
}

.question-prompt {
  font-size: 12px;
  color: #999999;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #F3F4F6;
}

/* 选项列表（每个选项独占一行） */
.options-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 20px;
}

.option-btn {
  width: 100%;
  padding: 16px 20px;
  background: #F9FAFB;
  border: 1px solid #E5E7EB;
  border-radius: 12px;
  text-align: left;
  font-size: 16px;
  color: #1F2937;
  cursor: pointer;
  transition: all 0.2s;
}

.option-btn:hover:not(:disabled) {
  background: #F3F4F6;
  border-color: #D1D5DB;
}

.option-selected {
  background: #EFF6FF;
  border-color: #93C5FD;
  color: #1E40AF;
  font-weight: 500;
}

/* 答案反馈样式 */
.option-correct {
  background: #ECFDF5;
  border-color: #A7F3D0;
  color: #059669;
  font-weight: 500;
}

.option-incorrect {
  background: #FEF2F2;
  border-color: #FECACA;
  color: #DC2626;
  font-weight: 500;
}

/* 膨胀动画效果 */
.option-highlight {
  animation: pulse 0.5s ease-in-out;
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.03);
  }
  100% {
    transform: scale(1);
  }
}

/* 不认识按钮 */
.dont-know-btn {
  width: 100%;
  padding: 16px 20px;
  background: #FEF3F2;
  border: 1px solid #FEE2E2;
  border-radius: 12px;
  text-align: left;
  font-size: 16px;
  color: #DC2626;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  gap: 10px;
}

.dont-know-btn:hover:not(:disabled) {
  background: #FEE2E2;
}

.dont-know-btn.btn-active {
  background: #FEE2E2;
  border-color: #FCA5A5;
  font-weight: 500;
}

.icon-unknown::before {
  content: '?';
  display: inline-block;
  width: 20px;
  height: 20px;
  background: #EF4444;
  color: white;
  border-radius: 50%;
  text-align: center;
  line-height: 20px;
  font-weight: bold;
}

/* 策略调整提示弹窗（Totast 效果） */
.strategy-tip {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%) scale(0.8);
  opacity: 0;
  z-index: 100; /* 保持高层级，显示时能覆盖其他内容 */
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 18px 24px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.15);
  transition: all 0.3s ease;
  max-width: 80%;

  /* 新增：隐藏时移除交互和可见性 */
  visibility: hidden; /* 完全隐藏元素（区别于opacity，会移除占位） */
  pointer-events: none; /* 让鼠标“穿透”弹窗，不拦截点击 */
}

/* 提示显示状态 */
.tip-show {
  opacity: 1;
  transform: translate(-50%, -50%) scale(1);
  visibility: visible; /* 显示元素 */
  pointer-events: auto; /* 恢复点击交互（弹窗内按钮可用） */
}

/* 降级提示样式（红色系） */
.tip-type-down .tip-icon {
  color: #DC2626;
  font-size: 24px;
}

.tip-type-down .tip-title {
  color: #DC2626;
  font-weight: 600;
}

/* 升级提示样式（绿色系） */
.tip-type-up .tip-icon {
  color: #059669;
  font-size: 24px;
}

.tip-type-up .tip-title {
  color: #059669;
  font-weight: 600;
}

.tip-content {
  flex: 1;
}

.tip-desc {
  font-size: 14px;
  color: #6B7280;
  margin-top: 4px;
}

/* 测试数据状态栏样式 */
.test-stats-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #F9FAFB;
  border-radius: 8px;
  margin-top: 15px;
  font-size: 12px;
}

/* 单个数据项样式 */
.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

/* 图标与文字色彩区分 */
.stat-item i {
  font-size: 14px;
  width: 16px;
  text-align: center;
}

.stat-label {
  color: #6B7280;
}

.stat-value {
  font-weight: 600;
  min-width: 16px;
  text-align: center;
}

/* 不同状态色彩 */
.stat-item.correct i,
.stat-item.correct .stat-value {
  color: #059669; /* 正确-绿色 */
}

.stat-item.wrong i,
.stat-item.wrong .stat-value {
  color: #DC2626; /* 错误-红色 */
}

.stat-item.guess i,
.stat-item.guess .stat-value {
  color: #F59E0B; /* 猜测-橙色 */
}

.stat-item.error-streak i,
.stat-item.error-streak .stat-value {
  color: #9333EA; /* 连错-紫色 */
}

/* 响应式调整（小屏幕换行） */
@media (max-width: 375px) {
  .test-stats-bar {
    flex-wrap: wrap;
    gap: 8px;
    padding: 10px 12px;
  }

  .stat-item {
    flex: 1;
    justify-content: center;
  }
}

/* 响应式调整 */
@media (max-width: 480px) {
  .test-card {
    max-height: none;
    height: 100%;
  }

  .question-word {
    font-size: 24px;
  }

  .option-btn, .dont-know-btn {
    padding: 14px 16px;
    font-size: 15px;
  }

  .strategy-tip {
    padding: 14px 20px;
    gap: 10px;
  }

  .tip-icon {
    font-size: 20px;
  }

  .tip-title {
    font-size: 16px;
  }

  .tip-desc {
    font-size: 13px;
  }
}
</style>
